﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Xml;

namespace TextEditor.TextDocument.Data.Knowledge
{
    public class DataTableFromToXml
    {
        /// <summary>
        /// 将DataTable对象转换成XML字符串
        /// </summary>
        /// <param name="xmlDT">DataTable对象</param>
        /// <returns>XML字符串</returns>
        public static string ConvertDataTableToXML(DataTable xmlDT)
        {
            MemoryStream stream = null;
            XmlTextWriter writer = null;
            try
            {
                stream = new MemoryStream();
                writer = new XmlTextWriter(stream, Encoding.Default);//根据stream实例化writer
                xmlDT.TableName = "dt";
                xmlDT.WriteXml(writer);//获取DataTable中的数据
                int count = (int)stream.Length;
                byte[] arr = new byte[count];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(arr, 0, count);
                return Encoding.GetEncoding("gb2312").GetString(arr).Trim();//解决中文乱码问题
                //UTF8Encoding utf = new UTF8Encoding();
                //return utf.GetString(arr).Trim();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }

        /// <summary>
        /// 将Xml字符串转换成DataTable对象
        /// </summary>
        /// <param name="xmlData">Xml字符串</param>
        /// <returns>DataTable对象</returns>
        public static DataTable ConvertXMLToDataTable(string xmlData)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                DataSet xmlDS = new DataSet();
                stream = new StringReader(xmlData);//读取字符串中的信息
                reader = new XmlTextReader(stream);//获取stream中的数据
                xmlDS.ReadXml(reader);//DataSet获取Xmlrdr中的数据
                return xmlDS.Tables[0];
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
        }
    }
}
